package severlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import dao.UserMapper;
import model.User;
import util.SqlSessionUtil;


/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
/**
* @author 听风寂  ，林舒馨
* @date 2020/1/8
* @ClassName LoginServlet
*/
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		//保存session id 把username返回值保存到session当前会话中，名称为user，只要当前会话不过期，任何地方都可以访到
		request.getSession().setAttribute("user", username);
		SqlSession s=SqlSessionUtil.getSqlSession();
		UserMapper up =s.getMapper(UserMapper.class);
		User finduser = up.selectUser(username);
		JSONObject object=new JSONObject();
		PrintWriter out = response.getWriter();  
		if(finduser==null) {
			object.put("code","0");
		}else {
			if(finduser.getPassword().equals(password)) {
				object.put("code","1");
			}
			else {
				object.put("code","0");
			}	
		}
				
		String jsonStr = JSON.toJSONString(object);
		out.print(jsonStr);
		out.close();	
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
